import { NextApiRequest, NextApiResponse } from "next";
import { SolrResponse } from "~/types/solr";

const SOLR_HOST = process.env.SOLR_HOST as string

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const productId = req.query.id as string

  if (req.method === 'GET') {
    const types = ['bundling', 'discount_loading', 'merchandise']
    const queryParams = new URLSearchParams({
      q: `product_ids:${productId}`,
      rows: '1'
    })

    let programs: any[] = []

    for (const type of types) {
      queryParams.set('fq', `type_value_s:${type}`) 
      queryParams.append('fq', `active_b:true`)

      const response = await fetch(`${SOLR_HOST}/solr/promotion_program_lines/select?${queryParams.toString()}`)
      const data: SolrResponse<any[]> = await response.json()
      programs.push(...data.response.docs)
    }

    programs = await extractPrograms(programs)
    res.status(200).json({ data: programs })
  }
}

const extractPrograms = async (programs: any[]) => {
  const result = []

  for (const program of programs) {
    const data: any = {}

    data.id = program.id
    data.program_id = program.program_id_i
    data.name = program.name_s
    data.type = {
      value: program.type_value_s,
      label: program.type_label_s,
    }
    data.limit = program.package_limit_i
    data.limit_user = program.package_limit_user_i
    data.limit_trx = program.package_limit_trx_i
    data.price = program.price_f
    data.total_qty = program.total_qty_i

    data.products = JSON.parse(program.products_s)
    data.free_products = JSON.parse(program.free_products_s)

    result.push(data)
  }

  return result
}